<template>
  <div class="evaluationInfo_container">
    <el-card
      class="box-card"
      shadow="always"
      style="background: #fafafa"
      v-if="routerVal == '0'"
    >
      <template #header>
        <div class="card-header" style="padding-bottom: 4px">
          <span>基本信息</span>
        </div>
      </template>
      <div>
        <el-form
          ref="elderFormRef"
          :model="form"
          :rules="rules"
          label-width="110px"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item
                label="客户姓名:"
                prop="applyId"
                style="font-weight: 700"
              >
                <el-select
                  v-model="form.homeBedApplyId"
                  clearable
                  filterable
                  placeholder="请选择客户姓名"
                  @change="changePeole"
                  style="width: 100%"
                >
                  <el-option
                    v-for="dict in applyPeople"
                    :key="dict.id"
                    :label="dict.applyName"
                    :value="dict.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别:" style="font-weight: 700">
                <span style="margin-left: 10px; font-weight: 400">
                  {{
                    sys_user_sex.find((item) => item.value == form.sex)
                      ? sys_user_sex.find((item) => item.value == form.sex)
                          .label
                      : ""
                  }}
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="年龄:" style="font-weight: 700">
                <span style="font-weight: 500">{{ form.age }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机号码:" prop="telephone">
                <el-input
                  v-model="form.telephone"
                  placeholder="请输入手机号码"
                />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="服务地址:" style="font-weight: 700">
                <el-select
                  v-model="form.livingAddrProvinceId"
                  placeholder="选择省"
                  style="width: 180px"
                  @change="changelivingProvince"
                >
                  <el-option
                    v-for="dict in livingRegionList"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.areaCode"
                  ></el-option>
                </el-select>
                <el-select
                  v-model="form.livingAddrCityId"
                  placeholder="选择市"
                  style="width: 180px; margin-left: 5px"
                  @change="changelivingCity"
                >
                  <el-option
                    v-for="dict in livingCityList"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.areaCode"
                  ></el-option>
                </el-select>
                <el-select
                  v-model="form.livingAddrCountyId"
                  placeholder="选择区/县"
                  style="width: 180px; margin-left: 5px"
                  @change="changelivingCounty"
                >
                  <el-option
                    v-for="dict in livingCountyList"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.areaCode"
                  ></el-option>
                </el-select>

                <el-select
                  v-model="form.livingAddrStreetId"
                  placeholder="选择乡村街道"
                  style="width: 180px; margin-left: 5px"
                  @change="changelivingStreet"
                >
                  <el-option
                    v-for="dict in livingStreetList"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.areaCode"
                  ></el-option>
                </el-select>

                <el-select
                  v-model="form.livingAddrCommunityId"
                  placeholder="选择乡村社区"
                  style="width: 250px; margin-left: 5px"
                  @change="changelivingCommunity"
                >
                  <el-option
                    v-for="dict in livingAddrCommunity"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.areaCode"
                  ></el-option>
                </el-select>
                <el-input
                  v-model="form.livingDetailAddress"
                  style="width: 450px; margin-left: 10px"
                  placeholder="请输入家庭详细地址"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <el-card
      class="box-card"
      shadow="always"
      style="background: #fafafa"
      v-else
    >
      <template #header>
        <div class="card-header" style="padding-bottom: 4px">
          <span>基本信息</span>
        </div>
      </template>
      <div>
        <el-form
          ref="elderFormRef"
          :model="form"
          :rules="rules"
          label-width="110px"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item label="客户姓名:" style="font-weight: 700">
                <span style="font-weight: 500">{{ form.applyName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别:" style="font-weight: 700">
                <span style="font-weight: 500">
                  {{
                    sys_user_sex.find((item) => item.value == form.sex)
                      ? sys_user_sex.find((item) => item.value == form.sex)
                          .label
                      : ""
                  }}</span
                >
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="年龄:" style="font-weight: 700">
                <span style="font-weight: 500">{{ form.age }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系电话:" style="font-weight: 700">
                <span style="font-weight: 500">{{ form.telephone }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="服务地址:" style="font-weight: 700">
                <span style="font-weight: 500">{{ form.address }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="服务状态:" style="font-weight: 700">
                <span style="font-weight: 500">
                  {{
                    order_status.find((item) => item.value == form.status)
                      ? order_status.find((item) => item.value == form.status)
                          .label
                      : ""
                  }}
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="下单时间:" style="font-weight: 700">
                <span style="font-weight: 500">{{ orderTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工单编号:" style="font-weight: 700">
                <span style="font-weight: 500">{{ form.workOrderCode }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <el-card
      class="box-card"
      shadow="always"
      style="background: #fafafa; margin-top: 20px"
    >
      <template #header>
        <div class="card-header" style="padding-bottom: 4px">
          <div
            class="card-header"
            style="
              padding-bottom: 4px;
              display: flex;
              align-items: center;
              justify-content: space-between;
            "
          >
            <span>服务项目</span>
          </div>
        </div>
      </template>
      <div>
        <el-table
          v-loading="loading"
          :data="servicePlanList"
          stripe
          border
          max-height="250"
        >
          <el-table-column label="服务项目" align="center" width="300">
            <template #default="scope">
              <el-select
                :disabled="disableFlag == '2' ? true : false"
                v-model="form.serviceItemId"
                clearable
                @change="
                  (value) => changeServiceName(value, scope.$index, scope.row)
                "
                placeholder="请选择服务项目"
                style="width: 250px"
              >
                <el-option
                  v-for="dict in serviceList"
                  :key="dict.serviceItemId"
                  :label="dict.serviceItemName"
                  :value="dict.serviceItemId"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="单价（元）"
            align="center"
            prop="unitPrice"
            width="100"
          />
          <el-table-column label="单位" align="center" width="100">
            <template #default="scope">
              <span>
                {{
                  bed_uint.find((item) => item.value == scope.row.unit)
                    ? bed_uint.find((item) => item.value == scope.row.unit)
                        .label
                    : ""
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="社区站点佣金（元）"
            width="160"
            align="center"
            prop="commission"
          ></el-table-column>
          <el-table-column label="计划开始时间" align="center" width="260">
            <template #default="scope">
              <el-date-picker
                :disabled="disableFlag == '2' ? true : false"
                v-model="form.planBeginTime"
                type="datetime"
                placeholder="请选择计划开始时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                time-format="HH:mm"
              />
            </template>
          </el-table-column>
          <el-table-column label="计划结束时间" align="center" width="260">
            <template #default="scope">
              <el-date-picker
                v-model="form.planEndTime"
                type="datetime"
                :disabled="disableFlag == '2' ? true : false"
                placeholder="请选择计划结束时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                time-format="HH:mm"
              />
            </template>
          </el-table-column>

          <el-table-column label="服务方" align="center" width="550">
            <template #default="scope">
              <span>
                <el-select
                  v-model="form.communitySiteId"
                  clearable
                  :disabled="disableFlag == '2' ? true : false"
                  @change="changeCommunity"
                  placeholder="请选择社区站点"
                  style="width: 250px"
                >
                  <el-option
                    v-for="dict in CommunityList"
                    :key="dict.id"
                    :label="dict.nameAndPhone"
                    :value="dict.id"
                  ></el-option>
                </el-select>
              </span>
              <span style="margin-left: 10px">
                <el-select
                  v-model="form.communitySitePersonnelId"
                  clearable
                  :disabled="disableFlag == '2' ? true : false"
                  placeholder="请选择站点人员"
                  style="width: 250px"
                >
                  <el-option
                    v-for="dict in people"
                    :key="dict.id"
                    :label="dict.nameAndPhone"
                    :value="dict.id"
                  ></el-option>
                </el-select>
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="合计金额（元）"
            prop="unitPrice"
            align="center"
          ></el-table-column>
        </el-table>
      </div>
    </el-card>
    <el-card
      class="box-card"
      shadow="always"
      style="background: #fafafa; margin-top: 15px"
    >
      <div
        style="text-align: right; padding-right: 50px"
        v-if="disableFlag == '1'"
      >
        <el-button
          type="primary"
          style="margin-left: 20px"
          @click="submitFormDebounceHandler"
          >保 存</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
      <div style="text-align: right; padding-right: 50px" v-else>
        <el-button @click="cancel">返 回</el-button>
      </div>
    </el-card>
  </div>
</template>
<script setup>
import { debounce } from '@/utils/debounce.js';

const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
import { region } from '@/api/record/api';
import {
  getCommunitySitePersonnelSelectOptions,
  getCommunitySiteSelectOptions,
  getWorkOrderCode,
  WorkOrdersave,
  WorkOrderupdate,
  WorkOrderInfo,
  getHomeBedApplyList,
  servicePlanInfo,
} from '@/api/order';
const { bed_uint, service_frequency, sys_user_sex, order_status } =
  proxy.useDict(
    'bed_uint',
    'service_frequency',
    'sys_user_sex',
    'order_status',
  )

const serviceList = ref([])
const servicePlanList = ref([
  {
    serviceItemId: '',
    commission: '',
    unitPrice: '',
    unit: '',
  },
])
const loading = ref(false)
const open = ref(false)
const postList = ref([])

const status = ref('');
const applyPeople = ref([])
const livingRegionList = ref([])
const livingCityList = ref([])
const livingCountyList = ref([])
const livingStreetList = ref([])
const livingAddrCommunity = ref([])
const serviceFrequency = ref('');
const CommunityList = ref([])
const people = ref([])
const orderTime = ref('');

const routerVal = ref('');
const disableFlag = ref('1');

const data = reactive({
  form: {},
  rules: {},
})
const { form, rules } = toRefs(data)

function cancel() {
  router.go(-1)
}
function getOrdPeople() {
  getHomeBedApplyList().then((res) => {
    applyPeople.value = res.homeBedApplyList
  });
}

const submitFormDebounceHandler = debounce(submitForm, 500)

function submitForm() {
  if(!form.value.homeBedApplyId){
    proxy.$modal.msgError('请输入客户姓名');
    return false
  }
  if(!form.value.serviceItemId){
    proxy.$modal.msgError('请选择服务项目');
    return false
  }
  if (!form.value.planBeginTime) {
    proxy.$modal.msgError('请输入计划开始时间');
    return false
  }
  if (!form.value.planEndTime) {
    proxy.$modal.msgError('请输入计划结束时间');
    return false
  }
  if (form.value.planBeginTime > form.value.planEndTime) {
    proxy.$modal.msgError('计划开始时间不能大于计划结束时间');
    return false
  }
  if (serviceFrequency.value == '0') {
    const satrt = form.value.planBeginTime.substring(0, 10)
    const end = form.value.planEndTime.substring(0, 10)
    if (satrt != end) {
      proxy.$modal.msgError(
        '改服务项目的服务频率是每天,计划开始时间和计划结束时间必须是同一天',
      )
      return false
    }
  }

  form.value.communitySiteName = CommunityList.value.find(
    (item) => item.id == form.value.communitySiteId,
  )?.name
  form.value.communitySitePersonnelName = people.value.find(
    (item) => item.id == form.value.communitySitePersonnelId,
  )?.name
  if (routerVal.value == '0') {
    WorkOrdersave(form.value).then((res) => {
      proxy.$modal.msgSuccess('新增成功');
      router.push('/ticketManagement/orderManagement');
    })
  } else {
    WorkOrderupdate(form.value).then((res) => {
      proxy.$modal.msgSuccess('修改成功');
      router.push('/ticketManagement/orderManagement');
    })
  }
}
async function changePeole(val) {
  const obj = applyPeople.value.find((item) => item.id == val)

  const data4 = await region(obj.livingAddrProvinceId)
  const data5 = await region(obj.livingAddrCityId)
  const data6 = await region(obj.livingAddrCountyId)
  const data7 = await region(obj.livingAddrStreetId)
  livingCityList.value = data4.data
  livingCountyList.value = data5.data
  livingStreetList.value = data6.data
  livingAddrCommunity.value = data7.data

  form.value.applyName = obj.applyName
  form.value.telephone = obj.telephone
  form.value.sex = obj.sex
  form.value.age = obj.age
  form.value.livingAddrProvinceId = obj.livingAddrProvinceId
  form.value.livingAddrProvinceName = obj.livingAddrProvinceName
  form.value.livingAddrCityId = obj.livingAddrCityId
  form.value.livingAddrCityName = obj.livingAddrCityName
  form.value.livingAddrCountyId = obj.livingAddrCountyId
  form.value.livingAddrCountyName = obj.livingAddrCountyName
  form.value.livingAddrStreetId = obj.livingAddrStreetId
  form.value.livingAddrStreetName = obj.livingAddrStreetName
  form.value.livingAddrCommunityId = obj.livingAddrCommunityId
  form.value.livingAddrCommunityName = obj.livingAddrCommunityName
  form.value.livingDetailAddress = obj.livingDetailAddress
  await getServiceItemSelectOptionsData(val)
  form.value.serviceItemId = '';
  servicePlanList.value = [
    {
      serviceItemId: '',
      commission: '',
      unitPrice: '',
      unit: '',
    },
  ]
}
async function getWorkOrderInfo(id) {
  const res = await WorkOrderInfo(id)
  await getServiceItemSelectOptionsData(res.workOrderInfo.homeBedApplyId)
  await CommunitySitePersonnelSelectOptions(res.workOrderInfo.communitySiteId)
  const data = await servicePlanInfo(res.workOrderInfo.homeBedApplyId);
  orderTime.value = res.workOrderInfo.createTime
  const obj = data.servicePlanInfo.servicePlanList.find(
    (item) => item.serviceItemId == res.workOrderInfo.serviceItemId,
  )
  servicePlanList.value = [
    {
      serviceItemId: obj.serviceItemId,
      commission: obj.commission,
      unitPrice: obj.unitPrice,
      unit: obj.unit,
    },
  ]
  form.value = res.workOrderInfo
  delete form.value.createTime
}
function changelivingProvince(val) {
  form.value.livingAddrProvinceName = livingRegionList.value.find(
    (item) => item.areaCode == val,
  )?.name
  livingCityList.value = []
  form.value.livingAddrCityId = '';
  form.value.livingAddrCountyId = '';
  form.value.livingAddrStreetId = '';
  form.value.livingAddrCommunityId = '';
  livingCountyList.value = []
  livingStreetList.value = []
  region(val).then((res) => {
    livingCityList.value = res.data
  });
}
function changelivingCity(val) {
  form.value.livingAddrCityName = livingCityList.value.find(
    (item) => item.areaCode == val,
  )?.name
  form.value.livingAddrCountyId = '';
  form.value.livingAddrStreetId = '';
  form.value.livingAddrCommunityId = '';
  livingCountyList.value = []
  livingStreetList.value = []
  region(val).then((res) => {
    livingCountyList.value = res.data
  });
}
function changelivingCounty(val) {
  form.value.livingAddrCountyName = livingCountyList.value.find(
    (item) => item.areaCode == val,
  )?.name
  form.value.livingAddrStreetId = '';
  form.value.livingAddrCommunityId = '';
  livingStreetList.value = []

  region(val).then((res) => {
    livingStreetList.value = res.data
  });
}
function changelivingStreet(val) {
  form.value.livingAddrStreetName = livingStreetList.value.find(
    (item) => item.areaCode == val,
  )?.name
  livingAddrCommunity.value = []
  form.value.livingAddrCommunityId = '';
  region(val).then((res) => {
    livingAddrCommunity.value = res.data
  });
}
function changelivingCommunity(val) {
  form.value.livingAddrCommunityName = livingAddrCommunity.value.find(
    (item) => item.areaCode == val,
  )?.name
}
function getregion() {
  region(0).then((res) => {
    livingRegionList.value = res.data
  });
}
function changeCommunity(val) {
  if(val){
    CommunitySitePersonnelSelectOptions(val)
  }

}
function CommunitySiteSelectOptionsData() {
  getCommunitySiteSelectOptions().then((res) => {
    CommunityList.value = res.communitySiteList
  });
}
function CommunitySitePersonnelSelectOptions(id) {
  getCommunitySitePersonnelSelectOptions(id).then((res) => {
    people.value = res.communitySitePersonnelList
  });
}
getregion()
getOrdPeople()
CommunitySiteSelectOptionsData()

function changeServiceName(val, index, data) {
  data.commission = serviceList.value.find(
    (item) => item.serviceItemId == val,
  )?.commission
  data.unitPrice = serviceList.value.find(
    (item) => item.serviceItemId == val,
  )?.unitPrice
  data.unit = serviceList.value.find((item) => item.serviceItemId == val)?.unit
  data.serviceItemName = serviceList.value.find(
    (item) => item.serviceItemId == val,
  )?.name
  serviceFrequency.value = serviceList.value.find(
    (item) => item.serviceItemId == val,
  )?.serviceFrequency
  form.value.totalPrice = serviceList.value.find(
    (item) => item.serviceItemId == val,
  )?.unitPrice
  form.value.serviceFrequency = serviceList.value.find(
    (item) => item.serviceItemId == val,
  )?.serviceFrequency
}
function getServiceItemSelectOptionsData(id) {
  servicePlanInfo(id).then((res) => {
    serviceList.value = res.servicePlanInfo.servicePlanList
  });
}
function workOrderCode() {
  if (routerVal.value == '0') {
    getWorkOrderCode().then((res) => {
      form.value.workOrderCode = res.workOrderCode
    });
  }
}

const stopWatch = watch(
  () => route,
  (newVal, oldVal) => {
    routerVal.value = newVal.params.id
    disableFlag.value = newVal.params.status
    if (routerVal.value != '0') {
      getWorkOrderInfo(routerVal.value)
    }
    workOrderCode()
  },
  { immediate: true },
)
// getServiceItemSelectOptionsData();
onBeforeUnmount(() => {
  stopWatch()
});
</script>
<style scoped lang="scss">
.evaluationInfo_container {
  padding: 20px;
}
</style>
